package com.meiqiongproperty.yiguanjia.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.meiqiongproperty.yiguanjia.commom.YApplication;
import com.meiqiongproperty.yiguanjia.db.utils.DBUserUtils;
import com.meiqiongproperty.yiguanjia.httpbean.UserInfo;
import com.meiqiongproperty.yiguanjia.ui.dialog.PersonalCenterAlertDialog;
import com.meiqiongproperty.yiguanjia.ui.dialog.SweetAlertDialog;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.meiqiongproperty.yiguanjia.db.utils.DBUserUtils.getUserInfo;
import static com.meiqiongproperty.yiguanjia.db.utils.DBUserUtils.getmDefaultHouse;

/**
 * 工具类  一般处理转型等操作
 *
 * @author Chen
 * @version V1.0
 * @package com.sameway.cnotes.utils
 * @date 17/1/13
 */
public class Utils<T> {
    /**
     * 判断字串是否为空
     *
     * @param str
     * @return
     */
    public static boolean emptyOrNull(String str) {
        return str == null || str.length() == 0;
    }

    /**
     * 将string 转为double,异常时返回-1
     *
     * @param s
     * @return
     */
    public static double toDouble(String s) {
        double i = 0;
        try {
            i = Double.parseDouble(s);
        } catch (Exception e) {
            i = -1;
        }
        return i;
    }

    public static double toDouble(Object obj) {
        if (obj != null && !"".equals(obj)) {
            return Double.parseDouble(obj.toString());
        }
        return 0.0;
    }

    public static String toString(Object obj) {
        if (obj != null && !"".equals(obj)) {
            return obj.toString();
        }
        return "";
    }

    // 将部分文字变成*号
    public static String replaceToXing(String content, int start, int end) {
        String newContent = "";
        if (content != null && !"".equals(content)) {
            String startStr = "";
            String endStr = "";
            String replaceStr = "";
            String str1 = "";

            int length = content.length();
            LogUtil.d("replaceToXing---content-->" + content + "start---->"
                    + start + "end----->" + end + "length--->" + length);

            if (start < length && end < length && start <= end) {
                startStr = content.substring(0, start - 1);
                LogUtil.d("replaceToXing--startStr----->" + startStr);
                endStr = content.substring(end);
                LogUtil.d("replaceToXing---endStr----->" + endStr);
                replaceStr = content.substring(start - 1, end);
                LogUtil.d("replaceToXing---replaceStr----->" + replaceStr);

                for (int i = 0; i < replaceStr.length(); i++) {
                    str1 = "*" + str1;
                }
            }
            newContent = startStr + str1 + endStr;
        }
        return newContent;
    }

    public static int getScreenWidth(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Activity.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    public static int dp2px(int value) {
        return (int) (YApplication.getContext().getResources().getDisplayMetrics().density * value);
    }

    public static int sp2px(int value) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, value, YApplication.getContext().getResources().getDisplayMetrics());
    }

    /**
     * 格式化字符串
     *
     * @param format
     * @param args
     */
    public static String format(String format, int args) {
        return String.format(format, args);
    }

    public static Point getScreenSize(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Point point = new Point(wm.getDefaultDisplay().getWidth(), wm.getDefaultDisplay().getHeight());
        return point;
    }

    public static void setFullSpan(StaggeredGridLayoutManager.LayoutParams layoutParams) {
        if (layoutParams != null && !layoutParams.isFullSpan()) {
            layoutParams.setFullSpan(true);
        }
    }

    private static long lastClickTime;

    /**
     * 判断是否是连续点击
     *
     * @return 布尔类型
     */
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 3000) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public static void showDialog(Context context, String msg) {
        PersonalCenterAlertDialog dialog = new PersonalCenterAlertDialog(context);
        dialog.builder().setCanceledOnTouchOutside(false).setMsg(msg).setPositiveButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        }).show();
    }


    /**
     * 通用弹出提示框
     *
     * @param message
     */
    public static void ShowMsg(String message, Context context) {
        new SweetAlertDialog(context)
                .setContentText(message)
                .show();
    }
//
//    /**
//
//     * 通用弹出提示框
//     *
//     * @param message
//     */
//    public static void ShowMsg(String message, Context context) {
//        new SweetAlertDialog(context)
//                .setContentText(message)
//                .show();
//    }
////
//    /**
//     * 显示选择对话框
//     *
//     * @param context
//     * @param msg
//     * @param leftText
//     * @param RightText
//     * @param onLeftSweetClickListener
//     * @param onRightClickListener
//     */
//    public static void showTowSubmitDialog(final Context context, String msg, String leftText, String RightText, SweetAlertDialog.OnSweetClickListener onLeftSweetClickListener, SweetAlertDialog.OnSweetClickListener onRightClickListener) {
//        new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE)
//                .setContentText(msg)
//                .setTitleHide(false)
//                .setCancelText(leftText)
//                .setConfirmText(RightText)
//                .showCancelButton(true)
//                .setCancelClickListener(onLeftSweetClickListener)
//                .setConfirmClickListener(onRightClickListener).show();
//    }

    /**
     * 获取body
     *
     * @param body
     * @return
     */
    public static RequestBody getRequestBody(Object body) {
        Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), gson.toJson(body));
        return requestBody;
    }

    public static int toInteger(Object obj) {
        if (obj != null && !"".equals(obj)) {
            return Integer.parseInt(obj.toString());
        }
        return 0;
    }

    /**
     * 获取当前时间
     */
    public static String getData() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        String date = formatter.format(curDate);
        return date;
    }

    /**
     * 获取当前时间
     */
    public static String getYunyingData() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        String date = formatter.format(curDate);
        return date;
    }

    /**
     * 获取当前时间
     */
    public static String getLifeServiceData() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        String date = formatter.format(curDate);
        return date;
    }


    /**
     * 获取年份时间
     */
    public static String getYearData() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        String date = formatter.format(curDate);
        return date;
    }

    /**
     * 获取当前月份
     */
    public static String getMouthData() {
        SimpleDateFormat formatter = new SimpleDateFormat("MM");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        String date = formatter.format(curDate);
        return date;
    }

    /**
     * 获取当前月份
     */
    public static String getMouthDay() {
        SimpleDateFormat formatter = new SimpleDateFormat("dd");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        String date = formatter.format(curDate);
        return date;
    }


    public static void getRGB(int drawble, final View v, Context context) {
        final int[] rgb = new int[1];
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), drawble);
        Palette.Builder builder = Palette.from(bitmap);
        builder.generate(new Palette.PaletteAsyncListener() {
            @Override
            public void onGenerated(Palette palette) {
                //获取到充满活力的这种色调
                Palette.Swatch vibrant = palette.getVibrantSwatch();
                v.setBackgroundColor(vibrant.getRgb());
            }
        });
    }

    /**
     * EditText把光标置在输入内容之后
     *
     * @param editText
     */
    public static void sectionAfter(EditText editText) {
        CharSequence text = editText.getText();
        //Debug.asserts(text instanceof Spannable);
        if (text instanceof Spannable) {
            Spannable spanText = (Spannable) text;
            Selection.setSelection(spanText, text.length());
        }
    }

    /**
     * 将中文标点替换为英文标点
     *
     * @return 替换后的文本
     */
    public static String replacePunctuation(String text) {
        text = text.replace('，', ',').replace('。', '.').replace('【', '[').replace('】', ']')
                .replace('？', '?').replace('！', '!').replace('（', '(').replace('）', ')').replace
                        ('“', '"').replace('”', '"');
        return text;
    }

    /**
     * 获取token
     */
    public static String getToken(Context context) {
        UserInfo.UserinfoBean info = getUserInfo(context);
        if (info != null) {
            return DBUserUtils.getUserInfo(context).getToken();
        }
        return null;
    }

    /**
     * 获取roomId
     */
    public static String getRoomID(Context context) {
        UserInfo.DefaultHouseBean info = getmDefaultHouse(context);
        if (info != null) {
            return info.getID();
        }
        return null;
    }

    /**
     * 获取用户手机号
     */
    public static String getUserPhoneNumber(Context context) {
        UserInfo.UserinfoBean info = getUserInfo(context);
        if (info != null) {
            return info.getMobile();
        }
        return null;
    }

    /**
     * 获取用户真实名称
     */
    public static String getUserRealName(Context context) {
        UserInfo.UserinfoBean info = getUserInfo(context);
        if (info != null) {
            return info.getRealName();
        }
        return null;
    }

    /**
     * 获取用户地址
     */
    public static String getUserAddress(Context context) {
        UserInfo.DefaultHouseBean info = getmDefaultHouse(context);
        if (info != null) {
            return info.getCommunityAddress();
        }
        return null;
    }

    /**
     * 获取管家手机号码
     */
    public static String getPropertyPhoneNumber(Context context){
        UserInfo.DefaultHouseBean info=getmDefaultHouse(context);
        if (info != null) {
            return info.getButlerPhone();
        }
        return null;
    }

    /**
     * 动态设置TextView图片位置
     */
    public static void setCompoundDrawablesWithTextView(Context context, TextView textView, int resource, String direction) {
        Drawable drawable = context.getResources().getDrawable(resource);
        switch (direction) {
            case "top":
                textView.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
                break;
            case "left":
                textView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
                break;
            case "bottom":
                textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, drawable);
                break;
            case "right":
                textView.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
                break;
        }

    }


    /**
     * 把int数值精确到小数点后两位
     */
    public static String numberPointTwo(int num) {
        Double number = toDouble(num);
        DecimalFormat b = new DecimalFormat("#0.00");
        return b.format(number);
    }

    /**
     * 精确到小数点后两位
     */
    public static String numberPointTwo(double number) {
        DecimalFormat b = new DecimalFormat("#0.00");
        return b.format(number);
    }

    public static String numberPointTwoStr(String num) {
        Double number = toDouble(num);
        return numberPointTwo(number);
    }

    /**
     * 截取小数点后两位
     */
    public static String numberSubThree(String number) {
        DecimalFormat b = new DecimalFormat("#0.000");
        String num = b.format(toDouble(number));
        return num.substring(0, num.length() - 1);
    }

    /**
     * 部分文字变色可点击  Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
     *
     * @param tv        TextView
     * @param spanClick click事件
     * @param start     开始位置
     * @param end       结束位置
     * @param spanned   它是用来标识在 Span 范围内的文本前后输入新的字符时是否把它们也应用这个效果。分别有 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE(前后都不包括)、Spanned.SPAN_INCLUSIVE_EXCLUSIVE(前面包括，后面不包括)、Spanned.SPAN_EXCLUSIVE_INCLUSIVE(前面不包括，后面包括)、Spanned.SPAN_INCLUSIVE_INCLUSIVE(前后都包括)。看个截图就更明白了：
     */
    public static void spannableText(TextView tv, ClickableSpan spanClick, int start, int end, int spanned, int color) {
        SpannableString spannableString1 = new SpannableString(tv.getText().toString());
        spannableString1.setSpan(spanClick, start, end, spanned);
        spannableString1.setSpan(new ForegroundColorSpan(color), start, end, spanned);
        tv.setText(spannableString1);
        tv.setMovementMethod(LinkMovementMethod.getInstance());
    }

    /**
     * 部分文字变色可点击  Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
     *
     * @param tv        TextView
     * @param start     开始位置
     * @param end       结束位置
     * @param spanned   它是用来标识在 Span 范围内的文本前后输入新的字符时是否把它们也应用这个效果。分别有 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE(前后都不包括)、Spanned.SPAN_INCLUSIVE_EXCLUSIVE(前面包括，后面不包括)、Spanned.SPAN_EXCLUSIVE_INCLUSIVE(前面不包括，后面包括)、Spanned.SPAN_INCLUSIVE_INCLUSIVE(前后都包括)。看个截图就更明白了：
     */
    public static void spannableText(TextView tv, View.OnClickListener listener,int start, int end, int spanned, int color) {
        tv.setOnClickListener(listener);
        SpannableString spannableString1 = new SpannableString(tv.getText().toString());
        spannableString1.setSpan(null, start, end, spanned);
        spannableString1.setSpan(new ForegroundColorSpan(color), start, end, spanned);
        tv.setText(spannableString1);
        tv.setMovementMethod(LinkMovementMethod.getInstance());
    }
}
